import Vue from "vue";
import router, { asyncRoutes } from "./router";
import store from "./store";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
const _ = require("lodash");

NProgress.configure({ showSpinner: false }); // NProgress配置：关闭进度环

/* 检查是否有路由 */
const checkoutRoutes = () => {
  const storeRoutes = store.state.permission.routes;
  return _.isArray(storeRoutes) && storeRoutes.length;
};
/* 创建路由 */
const createRoutes = async (to, from, next) => {
  try {
    const { roles } = await store.dispatch("user/getInfo"); // 获取当前用户的角色

    /* 根据用户信息生成对应动态权限树 */
    const rolesTree = store.state.user.rolesTree; // 菜单路由
    const customTree = store.state.user.customTree; // 自定义路由
    const accessRoutes = await store.dispatch("permission/generateRoutes", {
      rolesTree,
      customTree
    });
    router.addRoutes(accessRoutes);

    // hack method to ensure that addRoutes is complete
    // set the replace: true, so the navigation will not leave a history record
    next({ ...to, replace: true });
  } catch (error) {
    // 清除token并回到登录页
    await store.dispatch("user/resetToken");
    Vue.prototype.$mtMessage.error(error || "登录发生错误！");
    next(`/login?redirect=${to.path}`);
    NProgress.done();
  }
};
/* 获取前端白名单页面 */
const getWhiteList = () => {
  const whiteList = ["/login", "/queueScreen", "/selfCheckin"];
  const loopChildren = arr => {
    if (_.isArray(arr) && arr.length) {
      arr.forEach(item => {
        if (item.whiteList) whiteList.push(item.path);
        if (item.children) loopChildren(item.children);
      });
    }
  };
  asyncRoutes.forEach(item => {
    if (item.whiteList) whiteList.push(item.path);
    if (item.children) loopChildren(item.children);
  });
  return whiteList;
};
const whiteList = getWhiteList(); // 不需要权限的白名单

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  document.title = to.meta.title; // 设置页面title

  if (getToken()) {
    if (to.path === "/login") {
      // 如果携带token并且跳转至登录页, 则转至首页
      next({ path: "/" });
      NProgress.done();
    }
    else {
      if (checkoutRoutes()) next();
      else createRoutes(to, from, next);
    }
  }
  else {
    /* 本地不存在token情况 */
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
